package org.soma.sso.server.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.soma.sso.core.store.CookieStore;
import org.soma.sso.core.utils.HttpUtils;

import com.alibaba.fastjson.JSONObject;

public class SsoServerFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}


	@Override
	public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse, FilterChain filterChain)
		throws IOException, ServletException {
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			String cookieSessionId =CookieStore.getSessionIdByCookie(request);
			String buildCallbackURL = request.getRequestURL().toString();
			// response.sendRedirect("http://localhost:8080/login.html");
			 if(buildCallbackURL.endsWith("login.html") || buildCallbackURL.endsWith("verifyToken") || buildCallbackURL.endsWith("login")){
				 filterChain.doFilter(request, response);
			 }else{
				 response.sendRedirect("http://localhost:8080/login.html");
			 }
			if(StringUtils.isNotBlank(cookieSessionId)){
				 List<NameValuePair> params = new ArrayList<NameValuePair>();
		          params.add(new BasicNameValuePair("token", cookieSessionId));
				  String verifyToken= HttpUtils.sendPost("http://localhost:8080/sso/verifyToken", params);
				  JSONObject jsonObject = JSONObject.parseObject(verifyToken);
				  String resultObj =jsonObject.getString("resultObj");
				  if(verifyToken!=null && resultObj!=null && resultObj.equals("true")){//返回为空时表示当前登陆已经失效
					  filterChain.doFilter(request, response);
		          }
			 }
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}



}
